const { citys } = require('../../utils/city.js'); 
Page({
  data: {
    addressId: null, // 当前地址的 ID
    statusBarHeight: 0, // 状态栏高度
    detail: '', // 门牌号
    label: '', // 标签
    consignee: '', // 联系人
    sex: '', // 性别
    phone: '', // 手机号
    labelOptions: ['家', '公司', '学校', '父母家'], // 标签选项
    sexOptions: ['男', '女'], // 性别选项
    isDefault: false, // 是否设置为默认地址
    regionData: [],          // 原始数据
    provinces: [],           // 省份列表
    cities: [],              // 城市列表
    counties: [],            // 区县列表
    provinceIndex: 0,        // 当前选中省份索引
    cityIndex: 0,            // 当前选中城市索引
    countyIndex: 0,          // 当前选中区县索引
    selectedProvince: '',    // 选中省份名称
    selectedCity: '',        // 选中城市名称
    selectedCounty: ''       // 选中区县名称
  },
  
  // 返回按钮点击事件
  onBack: function () {
    wx.navigateBack({
      delta: 1
    });
  },

  onLoad: function (options) {
    const windowInfo = wx.getWindowInfo();
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight,
      regionData: citys || [],
      provinces: citys.map(p => p.name), // 初始化省份（字符串数组）
      addressId: options.addressId // 从页面跳转时传递的地址 ID
    });
    this.getAddressDetail(this.data.addressId);
  },

  // 获取地址详情
  getAddressDetail: function (addressId) {
    const app = getApp();
    const token = app.globalData.userInfo.token;

    wx.request({
      url: `http://localhost:8080/manage/address/${addressId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        console.log(res);
        if (res.statusCode === 200) {
          const address = res.data.data;
          this.setData({
            detail: address.detail,
            label: address.label,
            consignee: address.consignee,
            sex: address.sex,
            phone: address.phone,
            isDefault: address.isDefault === 1,
            selectedProvince: address.provinceName,
            selectedCity: address.cityName,
            selectedCounty: address.districtName
          });

          // 初始化省市区选择器
          this.initRegionPicker(address.provinceName, address.cityName, address.districtName);
        } else {
          wx.showToast({
            title: '获取地址详情失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 初始化省市区选择器
  initRegionPicker: function (provinceName, cityName, countyName) {
    const regionData = this.data.regionData;

    // 查找选中的省份
    const provinceIndex = regionData.findIndex(p => p.name === provinceName);
    if (provinceIndex === -1) return;

    const selectedProvince = regionData[provinceIndex];
    const cities = selectedProvince.city.map(c => c.name);

    // 查找选中的城市
    const cityIndex = selectedProvince.city.findIndex(c => c.name === cityName);
    if (cityIndex === -1) return;

    const selectedCity = selectedProvince.city[cityIndex];
    const counties = selectedCity.area;

    // 查找选中的区县
    const countyIndex = counties.findIndex(c => c === countyName);
    if (countyIndex === -1) return;

    // 设置数据
    this.setData({
      provinceIndex: provinceIndex,
      cityIndex: cityIndex,
      countyIndex: countyIndex,
      cities: cities,
      counties: counties
    });
    
  },

  // 省份选择变化
  onProvinceChange(e) {
    const index = e.detail.value;
    const selectedProvince = this.data.regionData[index];
    const cities = selectedProvince.city.map(c => c.name);
    const selectedCity = this.data.regionData[index].city[this.data.cityIndex];
    const counties = selectedCity.area;
    const selectedCounty = counties[this.data.countyIndex];
    this.setData({
      provinceIndex: index,
      cities: cities,
      counties: selectedProvince.city[0]?.area || [],
      selectedProvince: selectedProvince.name,
      selectedCity: selectedCity.name,
      selectedCounty: selectedCounty,
      cityIndex: 0,
      countyIndex: 0
    });
  },

  // 城市选择变化
  onCityChange(e) {
    const index = e.detail.value;
    const selectedCity = this.data.regionData[this.data.provinceIndex].city[index];
    const counties = selectedCity.area;
    const selectedCounty = counties[this.data.countyIndex];
    this.setData({
      cityIndex: index,
      counties: counties,
      selectedCity: selectedCity.name,
      selectedCounty: selectedCounty,
      countyIndex: 0
    });
  },

  // 区县选择变化
  onCountyChange(e) {
    const index = e.detail.value;
    this.setData({
      countyIndex: index,
      selectedCounty: this.data.counties[index] || ''
    });
  },
  // 输入框事件
  onInputDoorNumber: function (e) {
    this.setData({ detail: e.detail.value });
  },
  onInputConsignee: function (e) {
    this.setData({ consignee: e.detail.value });
  },
  onInputPhone: function (e) {
    this.data.phone=e.detail.value;
  },

  // 选择器事件
  onChangeLabel: function (e) {
    this.setData({ label: this.data.labelOptions[e.detail.value] });
  },
  onChangeSex: function (e) {
    this.setData({ sex: this.data.sexOptions[e.detail.value] });
  },

  onChangeDefault: function (e) {
    this.setData({
      isDefault: e.detail.value
    });
  },

  onSaveAddress: function () {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    const address = {
      id: this.data.addressId,
      userId: app.globalData.userInfo.id,
      consignee: this.data.consignee,
      sex: this.data.sex,
      phone: this.data.phone,
      provinceName: this.data.selectedProvince,
      cityName: this.data.selectedCity,
      districtName: this.data.selectedCounty,
      detail: this.data.detail,
      label: this.data.label,
      isDefault: this.data.isDefault ? 1 : 0 // 默认地址
    };
  
    // 如果设置为默认地址，先调用接口将所有地址设置为非默认
    if (this.data.isDefault) {
      wx.request({
        url: `http://localhost:8080/manage/address/clearDefault/${address.userId}`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        success: (res) => {
          if (res.statusCode === 200) {
            // clearDefault 成功后，再保存地址
            this.saveAddress(address);
          } else {
            wx.showToast({
              title: '清除默认地址失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        }
      });
    } else {
      // 如果不是默认地址，直接保存
      this.saveAddress(address);
    }
  },
  
  // 保存地址的公共方法
  saveAddress: function (address) {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    console.log(address);
    wx.request({
      url: 'http://localhost:8080/manage/address',
      method: 'PUT',
      data: address,
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '地址保存成功',
            icon: 'success'
          });
          // 获取父页面实例并手动刷新数据
          const pages = getCurrentPages();
          if (pages.length > 1) {
            const parentPage = pages[pages.length - 2];
            parentPage.getAddressList();
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 删除地址
  onDeleteAddress: function () {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗？',
      success(res) {
        if (res.confirm) {
          // 用户点击确定
          that.deleteAddress();
        } else if (res.cancel) {
          // 用户点击取消
          console.log('用户取消删除');
        }
      }
    });
  },

  deleteAddress: function () {
    const app = getApp();
    const token = app.globalData.userInfo.token;
    const addressId = this.data.addressId;
    wx.request({
      url: `http://localhost:8080/manage/address/${addressId}`,
      method: 'DELETE',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          wx.showToast({
            title: '地址删除成功',
            icon: 'success'
          });
          // 获取父页面实例并手动刷新数据
          const pages = getCurrentPages();
          if (pages.length > 1) {
            const parentPage = pages[pages.length - 2];
            parentPage.getAddressList();
          }
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            });
          }, 1500);
        } else {
          wx.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  }
});